package cn.zhx.xa.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;

import cn.zhx.xa.model.dto.role.SysRoleAddOrUpdateDto;
import cn.zhx.xa.model.dto.role.SysRoleSearchDto;
import cn.zhx.xa.model.entity.SysRole;
import cn.zhx.xa.model.vo.common.ResultCodeEnum;
import cn.zhx.xa.service.exception.BusinessException;
import cn.zhx.xa.system.dao.SysUserRoleDao;

import cn.zhx.xa.system.dao.SysRoleDao;
import cn.zhx.xa.system.service.SysRoleService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
* @author DELL
* @description 针对表【sys_role(角色)】的数据库操作Service实现
* @createDate 2024-01-30 12:46:54
*/
@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Resource
    private SysRoleDao sysRoleDao;

    @Resource
    private SysUserRoleDao sysUserRoleDao;

    @Override
    public Page<SysRole> findByPage(SysRoleSearchDto sysRoleSearchDto, Integer pageNum, Integer pageSize) {
        if(!ObjectUtil.isAllNotEmpty(pageNum,pageSize)){
            throw new BusinessException(ResultCodeEnum.DATA_ERROR);
        }
        //构造分页构造器
        Page pageInfo = new Page(pageNum, pageSize);
        return sysRoleDao.findByPage(pageInfo, sysRoleSearchDto);
    }

    @Override
    public void saveSysRole(SysRoleAddOrUpdateDto sysRoleAddDto) {
        SysRole role = new SysRole();
        BeanUtil.copyProperties(sysRoleAddDto,role);
        sysRoleDao.save(role);
    }

    @Override
    public void updateSysRole(SysRoleAddOrUpdateDto sysRoleUpdateDto) {
        sysRoleDao.updateSysRole(sysRoleUpdateDto) ;
    }

    @Override
    public void deleteById(Long roleId) {
        if(ObjectUtil.isEmpty(roleId)){
            throw new BusinessException(ResultCodeEnum.DATA_ERROR);
        }
        sysRoleDao.removeById(roleId);
    }

    @Override
    public Map<String, Object> findAllRoles(Long userId) {
        // 查询所有的角色数据
        List<SysRole> sysRoles = sysRoleDao.list();

        // 查询用户的角色数据
        List<Long> userRoles = sysUserRoleDao.findSysUserRoleByUserId(userId);

        Map<String , Object> resultMap = new HashMap<>() ;
        resultMap.put("allRolesList" , sysRoles) ;
        resultMap.put("userRolesList" , userRoles) ;
        return resultMap;
    }


}




